<template>
  <el-select
    v-model="modelValue"
    style="width: 100%"
    placeholder="点击选择用户"
    :multiple="multiple"
    :disabled="disabled"
    popper-class="dropdown"
    @visible-change="selectClick"
    @remove-tag="removeTag"
    @focus="focusClick"
  >
    <el-option
      v-for="{ userId, cname } of selectedRows"
      :key="userId"
      :label="`${cname}`"
      :value="userId"
    />
  </el-select>
  <el-dialog
    v-if="visible"
    v-model="visible"
    title="用户选择"
    custom-class="modal"
    append-to-body
    width="75%"
    top="10vh"
    @close="handleClose"
  >
    <el-row>
      <el-col :span="6" style="max-height: 600px; overflow: auto">
        <el-card shadow="never" class="tree">
          <!-- <el-input v-model="filterOrg" placeholder="筛选部门" style="margin-bottom: 10px" v-if="devType != 'platform'"/> -->
          <el-tree
            ref="tree"
            v-loading="treeLoading"
            :data="orgTree"
            node-key="id"
            :props="{ label: 'name', children: 'children' }"
            :filter-node-method="filterOrgTree"
            :default-expanded-keys="expandedKeys"
            :expand-on-click-node="false"
            @node-click="clickOrgTree"
          />
        </el-card>
      </el-col>
      <el-col :span="18">
        <search v-if="visible" @on-search="onSearch" :devType="devType" />
        <list
          v-if="visible"
          v-model="selectedRows"
          :list-data="listData"
          :multiple="multiple"
          @change-page="changePage"
          :devType="devType"
          :detailData="detailData"
          :loading="loading"
        />
      </el-col>
    </el-row>
    <template #footer>
      <el-button @click="onCancel">{{ $t('message.operate.cancel') }}</el-button>
      <el-button type="primary" @click="onOk">{{ $t('message.operate.confirm') }}</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { fetchListRequest } from '@/api/deptMember'
import { getOrgTree } from '@/api/position'
import { get, map } from 'lodash'
import List from './List'
import Search from './Search'
import { useStore } from 'vuex'
import { filter } from 'lodash'
import { servicesLoading } from '@/views/project/project-manage/loading'
import { getDeptByOrg } from '@/views/project/api/commom'
import { ElMessage } from 'element-plus'

export default {
  components: {
    Search,
    List,
  },
  props: {
    modelValue: {
      type: Object,
      required: true,
    },
    defaultUsers: {
      type: Array,
    },
    users: {
      type: Array,
      default() {
        return []
      },
    },
    multiple: {
      type: Boolean,
      default: true,
    },
    orgid: {
      type: String,
      default: '',
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    devType: {
      //平台模块使用
      type: String,
      default: '',
    },
    detailData: {
      //平台模块使用  回显数据
      type: String,
      default: '',
    },
    flag: {
      type: String,
      default: ''
    },
    onlyKey: {
      type: String,
      default: '',
    },
    selectIds: {
      type: Array,
      default: () => [],
    },
    noOrgTip:{
      type: Boolean,
      default: false,
    }
  },
  emits: ['update:modelValue', 'update:users', 'changePartake'],
  data() {
    return {
      visible: false,
      orgTree: [],
      expandedKeys: [],
      listData: {},
      selectedRows: {}, // 选中列表行
      params: {
        orgId: null,
        total: 0,
        size: 10,
        current: 1,
      },
      filterOrg: null,
      store: useStore(),
      treeLoading: false,
      loading: false,
    }
  },
  watch: {
    filterOrg(val) {
      this.$refs.tree?.filter(val)
    },
    visible() {
      if (this.visible) {
        this.getOrgs(this.orgid)
        // this.params.orgId = null
        // this.fetchList()
      }
    },
    orgid: {
      handler(newVal, oldVal) {
        console.log(newVal, 'orgid改变了')
        this.listData = []
        // this.getOrgs(newVal)
        // if (this.defaultUsers.length != 0) {
        //   this.selectedRows = this.defaultUsers
        //   this.saveValue()
        // } else {
        //   this.selectedRows = {}
        // }
      },
      immediate:true
    },
    defaultUsers: {
      handler(userList) {
        if (userList.length != 0) {
          this.selectedRows = userList
          console.log(this.selectedRows, 'this.selectedRows')
          // this.saveValue()
        } else {
          this.selectedRows = {}
        }
      },
      immediate: true,
      deep: true,
    },
  },
  mounted() {
    console.log(this.selectIds,'this.seleasdasdasdctIds');
    if (this.flag === 'add') {
      this.selectedRows = null;
    }
    // this.getOrgs()
    // this.saveValue()
    this.orgTree
  },
  methods: {
    handleClose() {
      console.log(this.params.orgId, 'this.params.orgId')
      // this.params.orgId = null
    },
    async getOrgs(orgId='') {
      try {
        this.treeLoading = true
        // const { data } = await getOrgTree()
        // const loading = servicesLoading({ fullscreen: true,text: '加载部门列表' })
        getDeptByOrg(orgId).then((res) => {
          this.orgTree = res.data.data
          console.log(this.orgTree,'getDeptByOrg');
          // loading.close()
          this.treeLoading = false
          if(orgId==''){
            this.params.orgId = this.orgTree[0].children[0].id
          }else{
            this.params.orgId = orgId
          }
          this.expandedKeys = map(get(this.orgTree[0], 'children', []), ({ id }) => id)
          this.fetchList()
        }).catch(()=>{
          // loading.close()
        })
      } catch (err) {
        console.error(err)
      }
    },
    async fetchList() {
      console.log(this.params, 'this.params')
      try {
        this.loading = true
        const { data } = await fetchListRequest(this.params)
        this.loading = false
        this.listData = get(data, 'data', {})
      } catch (err) {
        console.error(err)
      }
    },
    filterOrgTree(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    clickOrgTree({ id }) {
      // if (this.orgTree[0].id == id) {
      //   return
      // }
      this.params.orgId = id
      this.fetchList()
    },
    saveValue() {
      if (this.multiple) {
        const userIds = map(this.selectedRows, ({ userId }) => userId)
        const cname = map(this.selectedRows, ({ cname }) => cname)
        if (this.onlyKey === 'partake') this.$emit('changePartake', userIds ?? null, cname ?? null)
        else this.$emit('update:modelValue', userIds ?? null, cname ?? null)
        console.log('组件里的人员', this.selectedRows)
        // this.selectedRows = []
      } else {
        const userId = get(this.selectedRows, '[0].userId')
        const username = get(this.selectedRows, '[0].username')
        const cname = get(this.selectedRows, '[0].cname')
        const phone = get(this.selectedRows, '[0].phone')
        const gender = get(this.selectedRows, '[0].gender') //性别
        const gendertext = get(this.selectedRows, '[0].gendertext')
        const userCode = get(this.selectedRows, '[0].userCode')
        const email = get(this.selectedRows, '[0].email')
        if (userId) {
          this.$emit(
            'update:modelValue',
            { userId, username, cname, phone, gender, gendertext, userCode, email } ?? null
          )
        }
      }
      this.$emit('update:users', this.selectedRows)
    },
    onOk() {
      console.log('onOk')
      this.saveValue()
      this.visible = false
    },
    removeTag(tag) {
      console.log(tag, 'removeTag')
      console.log(this.selectedRows, 'this.selectedRows1')
      this.selectedRows = filter(this.selectedRows, ({ cname }) => cname !== tag)
      console.log(this.selectedRows, 'this.selectedRows2')
      this.saveValue()
    },
    focusClick(){
      if(this.noOrgTip){
        ElMessage({
          message: '请先选择单位信息',
          type: 'warning',
        })
      }
    },
    selectClick() {
      // #1802 - 双创活动业绩 - 回显修复
      if (this.onlyKey === 'partake') {
        console.log(this.selectIds,'this.selectIds');
        if(this.selectIds) {
          this.selectedRows = this.selectIds?.map((userId, index) => ({
            cname: this.modelValue[index],
            userId,
          }))
        }
        console.log(this.selectedRows, 123456)
      }
      if(this.noOrgTip){
        return
      }
      this.visible = true
    },
    onCancel() {
      console.log('onCancel')
      this.saveValue()
      this.visible = false
    },
    onSearch(form) {
      this.params = {
        ...this.params,
        ...form,
        current: 1,
      }
      this.fetchList()
    },
    changePage(page) {
      this.params = {
        ...this.params,
        current: page,
      }
      this.fetchList()
    },
  },
  beforeUnmount() {
    console.log('用户组件注销')
  },
}
</script>

<style lang="scss">
.modal {
  overflow: hidden;
}
.dropdown {
  display: none;
  .el-select-dropdown {
    display: none;
  }
}
</style>
<style lang="scss" scoped>
.tree {
  height: 100%;
  overflow: scroll;
}
</style>
